package cn.ywang.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Pub/Sub 发布订阅
 *
 * @author: BeatificWang
 * @date: 2018/12/22 17:04
 */
public class PubSubProducer {
	public static void main(String[] args) {
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		Connection connection = null;
		try {
			// 创建连接
			connection = factory.createConnection();
			//			connection.setClientID("wang");
			connection.start();
			// 第一个参数 transacted 代表是否开启事务 ture为开启 false为关闭
			Session session = connection.createSession(Boolean.TRUE, Session.CLIENT_ACKNOWLEDGE);
			// 目的地
			// Pub/Sub 分持久化和非持久化
			Destination destination = session.createTopic("myTopic");
			// 消息生产者
			MessageProducer producer = session.createProducer(destination);
			// 消息
			Message msg = session.createTextMessage("hello, wang");
			// 持久化消息，订阅者未激活时消息生产者发送消息，订阅者激活后可以收到消息
			//			msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
			producer.send(msg);
			session.commit();
			session.close();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
